package com.chainwintel.prjmgmt.service;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.chainwintel.prjmgmt.model.MenuItem;
import com.chainwintel.prjmgmt.model.User;
import com.chainwintel.prjmgmt.repository.GenericRepositoryImpl;

@Repository
@Transactional(readOnly = true)
public class MenuItemMgrImpl extends GenericRepositoryImpl<MenuItem> implements
		MenuItemMgr {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6478613900318905014L;

	public MenuItem find(long id) throws DataAccessException {
		// TODO Auto-generated method stub
		return this.find(MenuItem.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> listMenus() throws DataAccessException {
		// TODO Auto-generated method stub
		return getEntityManager().createQuery("select m from MenuItem m").getResultList();
	}
	
	

	@Transactional
	public void doAssign(User user, MenuItem menuItem) throws DataAccessException {
		// TODO Auto-generated method stub
		user = getEntityManager().merge(user);
		menuItem = getEntityManager().merge(menuItem);
		user.getOperations().add(menuItem);
	}

	@Transactional
	public void doUnassign(User user, MenuItem menuItem)
			throws DataAccessException {
		// TODO Auto-generated method stub
		user = getEntityManager().merge(user);
		menuItem = getEntityManager().merge(menuItem);
		user.getOperations().remove(menuItem);
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> listRootMenus() throws DataAccessException {
		// TODO Auto-generated method stub
		return getEntityManager().createQuery("select m from MenuItem m where m.parentMenu is null").getResultList();
	}

}

